package com.googlecode.quillen.service;

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;

/**
 * Created by IntelliJ IDEA.
 * User: greg
 * Date: Dec 6, 2008
 * Time: 8:03:55 PM
 */
public class CompressionServiceImpl implements CompressionService
{
    public byte[] compress(byte[] data) throws IOException
    {
        ByteArrayOutputStream result = new ByteArrayOutputStream(data.length);

        GZIPOutputStream out = new GZIPOutputStream(result);
        out.write(data);
        out.finish();
        out.close();

        return result.toByteArray();
    }

    public byte[] decompress(byte[] data) throws IOException
    {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        GZIPInputStream zip = new GZIPInputStream(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream(zip.available());

        byte[] buffer = new byte[zip.available()];

        int bytesRead;
        while ((bytesRead = zip.read(buffer)) > 0)
        {
            out.write(buffer, 0, bytesRead);
        }

        return out.toByteArray();
    }
}
